package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.regex.Matcher;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		HttpSession session = request.getSession();
		if(session.getAttribute("users")!=null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String[] listError = new String[5];
		request.setAttribute("listError", listError);
		
		try {
			request.getRequestDispatcher("/register.jsp").forward(request,response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		HttpSession session = request.getSession();
		if(session.getAttribute("users")!=null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		String email = request.getParameter("email");
		
		//validate
		String[] listError = new String[5];
		
		if(username!=null&&username.equals("")){
			listError[0]="Username is not empty !";
		}else{
			DBCollection collection = Data.data("users");
			DBObject dbObject = collection.findOne(new BasicDBObject("username",username));
			if(dbObject!=null)
				listError[0]="Username already exists !";
		}
		
		if(password!=null&&password.equals("")){
			listError[1]="Password is not empty !";
		}else{
			if(!password.equals(repassword))
				listError[2]="Confirm password incorrect !";
		}
		java.util.regex.Pattern p = java.util.regex.Pattern.compile(".+@.+\\.[a-z]+");
	    Matcher m = p.matcher(email);
	    boolean matchFound = m.matches();

	    if (!matchFound)
	    {
	    	listError[3] = "Invalid Email !";
	    } else {
	    	DBCollection collection = Data.data("users");
			DBObject dbObject = collection.findOne(new BasicDBObject("email",email));
			if(dbObject!=null)
				listError[3]="Email already exists !";
	    }
	    //check capchar
		String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6LcF-80SAAAAAM2kArjyUwtVJYbH_DKredY3Q26U");

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        if(challenge == null)
        {
        	challenge = "b";
        }
        if(uresponse == null)
        {
        	uresponse = "a";
        }
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
        	listError[4] = "Invalid Capchar";
        }
	    
	    //valid success
	    if(listError[0] == null && listError[1] == null && listError[2] == null && listError[3] == null&& listError[4] == null)
	    {
	    	DBCollection collection = Data.data("users");
	    	BasicDBObject basicDBObject = new BasicDBObject();
	    	basicDBObject.put("username", username);
	    	try {
				basicDBObject.put("password", Utils.md5(password));
			} catch (NoSuchAlgorithmException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
	    	basicDBObject.put("email", email);
	    	try {
				basicDBObject.put("code_active", Utils.md5(username));
			} catch (NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			}
	    	
			try {
				String mesage = "Dear "+email+"<br/><br/>" +
						"Thank you for registering at the Hatforrent Service System. Before we can activate your account one last step must be taken to complete your registration.<br/><br/>" +
						"Please note - you must complete this last step to become a registered member. You will only need to visit this URL once to activate your account.<br/><br/>" +
						"To complete your registration, please visit this URL:" +
						"<br/><a href='http://hatforrent.com/active/"+Utils.md5(username)+"'>http://hatforrent.com/active/"+Utils.md5(username)+"</a>" + 
						"<br/><br/><p>If you are still having problems signing up please contact a member of our support staff at support@hatforrent.com</p>" +
						"All the best,<br/>" +
						"Hatforrent Service System";
	            URL url = new URL("http://send-emails.appspot.com/sendemail");
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoOutput(true);
	            connection.setRequestMethod("POST");
	            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	            writer.write("email="+email);
	            writer.write("&name_email="+email);
	            writer.write("&from_email=admin@hatforrent.com");
	            writer.write("&subject=Action Required to Activate Membership for Hatforrent Service System");
	            writer.write("&content="+mesage);
	            writer.close();
	    
	            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            }
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			basicDBObject.put("coin", 450);
			basicDBObject.put("created", new Date().getTime());
			basicDBObject.put("status", "trial");
			basicDBObject.put("timeend", new Date().getTime()+30L*24L*60L*60L*1000L);
			collection.insert(basicDBObject);
			
			request.setAttribute("success", "Register success. Please check email active account !");
			
	    	
	    } else {
	    	request.setAttribute("username", username);
	    	request.setAttribute("email", email);

	    }
	    request.setAttribute("listError", listError);
	    try {
			request.getRequestDispatcher("/register.jsp").forward(request,response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
